<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class GouwucheController extends Controller
{
    //
    public function insert(Request $request)
    {
    	// dd($request->all());
    	//提取数据
    	$data = $request->only(['id','num']);
    	// dd($data);
    	//检测当前商品是否已经存在与购物车中
    	if($this->check($data['id'])){
    		//如果存在就修改数量
    		$goods = session('cart');
    		foreach($goods as $k=>$v)
    		{
    			if($v['id'] == $data['id']){
    				$goods[$k]['num'] += $data['num'];
    			}
    		}

    		//将更新后的数据重新session
    		session(['cart'=>$goods]);
    	}else{
    		//将当前数据压入到cart中
    		$request->session()->push('cart',$data);

    	}

    	return $data;

	}

	//检测方法
	private function check($id)
	{
		//提取购物车中的数据
		$goods = session('cart');
		// dd($goods);
		if(empty($goods)){
			return false;
		}

		foreach($goods as $k=>$v){
			if($v['id']==$id){
				//商品存在购物车中
				return true;
			}
		}

		//商品不存在返回false
		return false;
	}


	/*
		显示购物车信息
	 */
	public function index()
	{
		//提取当前所有的购物车商品	
		$goods = session('cart');

		$data = [];
		foreach($goods as $k=>$v){
			$tem = DB::table('goodsmain')->where('id',$v['id'])->first();
			$tem->num = $v['num'];
			$data[] = $tem;
		}
		// dd($data);
		$jiage = [];
    	foreach($data as $k=>$v){
    		if(empty($v->price)){
    			$jiage[]=$v->hwprice * $v->num;
    		}else{
    			$jiage[]=$v->price * $v->num;
    		}
    		
    	}
    	// dd($jiage);
    	$zongjia = '';
    	foreach($jiage as $v){
    		$zongjia+=$v;
    	}
		return view('home.gouwuche',['goods'=>$data,'zongjia'=>$zongjia]);
	}

	public function delete($id,Request $request)
	{
		//提取数据
  //   	$data = $request->only(['id']);
    	// dd($id);
		//提取当前所有的购物车商品	
		$goods = session('cart');
		// dd($goods);
		foreach($goods as $k=>$v){
			if($v['id']== $id){
				// session('cart')[$k]='';
				$request->session()->forget(session('cart')[$k]);
				dd(session('cart'));
			}
		}


	}
    	
    
}
